const path = require( 'path' );
const HtmlWebpackPlugin = require('html-webpack-plugin');
// 用于在生产环境下，生成 dist 中的文件之前清除 dist 文件内容
const CleanWebpackPlugin = require('clean-webpack-plugin');

// 这一份文件包含了生产环境以及开发环境的配置


module.exports = function(env){

  // 从 mode 里面解析出是生产环境还是开发环境
  let { mode } = env;



  const config = {
    entry: {
      app: './src/index.js'
    },
    output: {
      filename: '[name].[hash].js',
    },

    context: path.resolve(__dirname),
    devServer: {
      historyApiFallback: true,
      contentBase: path.join( __dirname, 'dist' )
    },

    module: {
      rules: [
        { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" },
        {
          test: /\.css$/,
          use: [
            { loader: "style-loader" },
            {
              loader: "css-loader"  // translates CSS into CommonJS
            }
          ]
        }, {
          test: /\.less$/,
          use: [ {
            loader: "style-loader" // creates style nodes from JS strings
          }, {
            loader: "css-loader",  // translates CSS into CommonJS
            options: {
              modules: true,
              importLoaders: 1,
              localIdentName: '[path]_[local]_[hash:base64:2]'
            }
          }, {
            loader: "less-loader" // compiles Less to CSS
          }
          ]
        }, {
          test: /\.(png|jpg|gif|svg)$/,
          use: [
            {
              loader: 'url-loader',
              options: {
                limit: 100000,
                mimetype: 'image/png'
              }
            }
          ]
        }

      ]

    },
    plugins: [ ]
  };



  if ( mode === 'dev') {

    config.output.path = path.resolve(__dirname, 'dist');

    // config.module.rules.push({
    //   test: /\.svg$/,
    //   use: [
    //     {
    //       loader: 'file-loader',
    //       options: {}
    //     }
    //   ]
    // });


    config.plugins.push( new HtmlWebpackPlugin(
      {
        template: 'src/template/dev.html'
      }) );


  }

  if ( mode === 'pro' ){
    // config.module.rules.push({
    //   test: /\.svg$/,
    //   use: [
    //     {
    //       loader: 'file-loader',
    //       options: {
    //         outputPath: 'images/',
    //         publicPath: 'static/images' // 由于反向代理的存在
    //       }
    //     }
    //   ]
    // });
    //
    // config.output.path = path.resolve(__dirname, '../tyBBS/static');
    //
    // config.plugins.push(
    //   new CleanWebpackPlugin(  path.resolve(__dirname, '../tyBBS/static'),
    //     { allowExternal: true } ) // 允许删除项目目录以外的文件
    // );
    //
    // config.output.publicPath = './static';
    //
    // // 为页面生成的html
    // config.plugins.push(
    //   new HtmlWebpackPlugin( {
    //     filename: 'template.html',
    //     template: 'src/templateForWebpackHtmlPlugins/pro/index.html'
    //   } )
    // );
  }


  return config;

};